<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/23
 * Time: 16:18
 */

namespace app\api\controller;


use think\cache\driver\Redis;
use think\Controller;
use think\Db;
use think\Exception;
use app\common\logic\Trend;
header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");
class Hall extends Controller{

    public function _initialize(){
        parent::_initialize();
        //验证加密
        $VALUE_KEY = ['afewfewfew21342dsaewf'=>'8f4da4f9ew4f98ewq65fwe48f9w'];
        $HEADER_TIME = isset($_SERVER['HTTP_TIME']) ? $_SERVER['HTTP_TIME'] : '';
        $HEADER_KEY = isset($_SERVER['HTTP_KEY']) ? $_SERVER['HTTP_KEY'] : '';
        $HEADER_SIGN = isset($_SERVER['HTTP_SIGN']) ? $_SERVER['HTTP_SIGN'] : '';

        $POST_LOGIN_KEY = isset($_SERVER['HTTP_LOGINKEY']) ? $_SERVER['HTTP_LOGINKEY'] : ( isset($_POST['login_key']) ? $_POST['login_key'] : '' );
        $POST_NAME = isset($_SERVER['HTTP_USERNAME']) ? $_SERVER['HTTP_USERNAME'] : (isset($_POST['username']) ? $_POST['username'] : (isset($_POST['name']) ? $_POST['name']:''));

        if( !isset($VALUE_KEY[$HEADER_KEY]) ){
            exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
        }
        $validation =  $HEADER_TIME.$VALUE_KEY[$HEADER_KEY].$POST_LOGIN_KEY.$POST_NAME;

        if( $HEADER_SIGN != md5($validation) ){
            exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
        }
    }

    public function classify(){

        $classify = Db::name("lottery_classify")->field('class_name_lottery,czids,mpic_on,mpic_off')->where(['status'=>1])->order("sorting ASC,id asc")->select();
        $category_rm = Db::name("caipai_list")->field(['GROUP_CONCAT(id)'=>'czids'])->where(['cp_if_open'=>1,'cp_dn_index'=>1])->find();
        $classifyAttr = [
            [
                'name' => '全部彩种',
                'img_on' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/static/template/sysme/images/hr.png',
                'img_off' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/static/template/sysme/images/hr_black.png',
                'czids' => !empty($category_rm) ? $category_rm['czids'] : ''
            ]
        ];
        foreach($classify as $v){
            $classifyAttr[] = [
                'name' => $v['class_name_lottery'],
                'img_on' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['mpic_on'],
                'img_off' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['mpic_off'],
                'czids' => $v['czids']
            ];
        }
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas'=>$classifyAttr
        );
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }

    public function index(){
        $classify = Db::name("lottery_classify")->field('class_name_lottery,czids,mpic_on,mpic_off')->where(['status'=>1])->order("sorting ASC,id asc")->select();
        $caipiao = Db::name("caipai_list")->where(['cp_if_open'=>1])->order("cp_mb_px ASC")->column('cp_name_old,cp_name_new,num_day,logo','id');
        $config = config("lotterys");
        foreach( $caipiao as &$v ){
            foreach($config as $k=>$val){
                in_array($v['id'],$val) && $v['abc'] = $k;
            }
        }
        unset($v);
        $format_cp = array_map(function($v){
            $v['name'] = empty($v['cp_name_new']) ? $v['cp_name_old'] : $v['cp_name_new'];
            $v['logo'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['logo'];
            unset($v['cp_name_new']);
            unset($v['cp_name_old']);
            return $v;
        },$caipiao);

        $all = [
            'class_name_lottery' => '全部彩种',
            'mpic_on' => 'static/template/sysme/images/hr.png',
            'mpic_off' => 'static/template/sysme/images/hr_black.png',
            'czids' => ''
        ];
        array_unshift($classify,$all);
        foreach( $classify as &$v){
            $czid = $v['czids'];
            $v['mpic_on'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['mpic_on'];
            $v['mpic_off'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['mpic_off'];
            $son = [];
            if( empty($czid) ){
                $son = array_values($format_cp);
            }else{
                $czid_attr = explode(',',$v['czids']);
                foreach($czid_attr as $val){
                    if( isset($format_cp[$val]) )$son[] = $format_cp[$val];
                }
            }
            unset($v['czids']);
            $v['son'] = $son;
        }
        unset($v);
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas'=>$classify
        );
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }

    public function lottery_list(){
        $ids = input('post.ids','');
        /**
         * 最新开奖结果（最大ID）
         */
        $max_id_query = Db::name('kjjg_list')
            ->field('MAX(id)')
            ->where('kjjg','>','0')
            ->group('czid')
            ->buildSql();
        /**
         * 最新开奖结果（详细信息）
         */
        $max_czid_query = Db::name('kjjg_list')
            ->field('czid,kjjg,qihao')
            ->where("id IN({$max_id_query})")
            ->buildSql();

        $caizhong = Db::name('caipai_list')->alias('a')
            ->join("{$max_czid_query} b",'a.id=b.czid')
            ->field('a.id,a.cp_name_old,a.cp_name_new,a.logo,b.kjjg,b.qihao,a.cp_dn_index,a.num_day')
            ->where('cp_if_open',1)
            ->where('id','in',$ids)
            ->order('cp_mb_px','DESC')
            ->select();
        $list = array();
        foreach ($caizhong as $v){
            $v['kjjg'] = kjjg_split($v['kjjg'], $v['id']);
            $a = 0;
            foreach ($v['kjjg'] as $ss){
                $a += $ss;
            }
            if($v['id']==36 || $v['id']==44){
                $v['kjjg'][] = '=';
                $v['kjjg'][] = $a;
            }
            $v['kjjg'] = implode( " ",$v['kjjg'] );
            $org_qh = $v['qihao'];
            $v['qi_hao']= $v['qihao'];

            $v['next'] = time();
            $next = new Redis();
            $v['between'] = 0;
            $v['qihao'] = '';
            $nextNo = $next->get($v['id']);
            if( $nextNo ){
                $nextAttr = explode(',',$nextNo);
                if($v['id']==62 || $v['id']==63 || $v['id']==72){
                    $v['qihao'] = substr(substr($nextAttr[0],4),-3);
                }else{
                    $v['qihao'] = substr($nextAttr[0],-3);
                }
                $v['next'] = $nextAttr[1];
                $before = Db::name('kjjg_list')->where(['czid'=>$v['id']])->where('jztime','<',$nextAttr[1])->order('qihao','DESC')->value('qihao');
                if($before && $before==$org_qh){
                    $v['between'] = $v['next']-time();
                }
            }else{
                $jztime_fur = Db::name('kjjg_list')->where(['czid'=>$v['id'],'kjjg'=>'0'])->where('jztime','>',time())->order('qihao','DESC')->field('qihao,jztime')->find();
                if($jztime_fur){
                    if($v['id']==62 || $v['id']==63 || $v['id']==72){
                        $v['qihao'] = substr(substr($jztime_fur['qihao'],4),-3);
                    }else{
                        $v['qihao'] = substr($jztime_fur['qihao'],-3);
                    }
                    $v['next'] = $jztime_fur['jztime'];
                    $before = Db::name('kjjg_list')->where(['czid'=>$v['id']])->where('jztime','<',$jztime_fur['jztime'])->order('qihao','DESC')->value('qihao');
                    if($before && $before==$org_qh){
                        $v['between'] = $v['next']-time();
                    }
                }
            }
            $v['logo'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['logo'];
            $v['cp_name'] = !empty($v['cp_name_new']) ? $v['cp_name_new'] : $v['cp_name_old'];
            $list[] = $v;
        }
        $ret = array(
            'result'=>0,
            'ResultMsg'=>'无信息',
        );
        if( count($list) > 0 ){
            $ret = array(
                'result'=>1,
                'ResultMsg'=>'',
                'datas' => $list
            );
        }
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function lottery(){
    	$pk10 = array('01'=>'#e5e500','02'=>'#2a64ae','03'=>'#949695','04'=>'#f29535','05'=>'#7dcbdf','06'=>'#2c489c','07'=>'#cbcbcb','08'=>'#e83338','09'=>'#421e20','10'=>'#4fb233');
        $lhc = array(
        		'red'=>'01,02,07,08,12,13,18,19,23,24,29,30,34,35,40,45,46',
        		'green'=>'05,06,11,16,17,21,22,27,28,32,33,38,39,43,44,49',
        		'blue'=>'03,04,09,10,14,15,20,25,26,31,36,37,41,42,47,48'
        );
        $max_id_query = Db::name('kjjg_list')
            ->field('MAX(id)')
            ->where('kjjg','>','0')
            ->group('czid')
            ->buildSql();

        $max_czid_query = Db::name('kjjg_list')
            ->field('czid,kjjg,qihao,jztime')
            ->where("id IN({$max_id_query})")
            ->buildSql();
        $caipai_list = Db::name('caipai_list')
            ->alias('a')
            ->join("{$max_czid_query} b",'b.czid=a.id')
            ->field("a.id,a.logo,a.cp_name_old,a.cp_name_new,b.kjjg,b.qihao,b.jztime,'' as color")
            ->where('a.cp_if_open<2')
            ->order('a.cp_mb_px ASC')
            ->select();
        $config = config("lotterys");
        foreach( $caipai_list as &$v ){
            foreach($config as $k=>$val){
                in_array($v['id'],$val) && $v['abc'] = $k;
            }
        }
        unset($v);
        foreach ($caipai_list as &$caipai_single) {
            $caipai_single['logo'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].DS.$caipai_single['logo'];
            $caipai_single['cp_name_new'] || $caipai_single['cp_name_new'] = $caipai_single['cp_name_old'];
            unset($caipai_single['cp_name_old']);
            $caipai_single['kjjg'] = kjjg_split($caipai_single['kjjg'], $caipai_single['id']);
            $a=0;
            $count = count($caipai_single['kjjg']);
            $enter = 0;
            if( 4==intval($caipai_single['id']) || 61==intval($caipai_single['id']) || 63==intval($caipai_single['id'])){
            	$caipai_single['color'] = $caipai_single['kjjg'];
            	foreach ($caipai_single['color'] as $key=>$t){
            		$caipai_single['color'][$key]=$pk10[$t];
            	}
            }
            foreach ($caipai_single['kjjg'] as $k=>$ss){
                $a+=$ss;
                if( in_array(intval($caipai_single['id']),[9,73])  && $count==$k+1 && 0==$enter ){
                    array_splice($caipai_single['kjjg'],$k,0,'+');
                    $enter = 1;
                }
            }
            if( in_array(intval($caipai_single['id']),[9,73]) ){
            	$caipai_single['color'] = $caipai_single['kjjg'];
            	foreach ($caipai_single['color'] as $key=>$t){
            		foreach ($lhc as $k=>$it){
            			if(strpos($it,$t)!==false){
            				$caipai_single['color'][$key]=$k;
            			}
            		}
            
            	}
            }
        }
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas' => $caipai_list
        );
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function raffle(){
        $ret = array(
            'result'=>0,
            'ResultMsg'=>'无信息',
        );
        $username = input('username','');
        $login_key = input('login_key','');
        $user = Db::name('username')->where(['username'=>$username,'login_key'=>$login_key])->where('open', '<', 1)->find();
        if( empty($user) ){
            $ret['ResultMsg'] = '请先登录!';
        }else{
            $user = Db::name("username")->where(['username'=>$username])->field('swzh,czzje,us_class')->find();
            if( 1==intval($user['swzh']) ){
                $ret['ResultMsg'] = '试玩账号无法参与抢红包!';
            }else{
                //查询红包开启时间和开启类型
                $on_lay = Db::name('bonus_lay')->find();
                if( 0==intval($on_lay['flip']) ){
                    $ret['ResultMsg'] = '红包暂未开启!';
                }elseif(strtotime($on_lay['start_time']) < time() && strtotime($on_lay['end_time']) > time()){
                    //获取用户抢红包次数
                	$cz = Db::name('chongzhi_list')->whereTime('cztime','today')->where(['username'=>$username,'zt'=>1])->value('SUM(je)');
                    $sum = 0;
                    $lay_sum = Db::name('bonus_num')->order('saving asc')->select();
                    foreach ($lay_sum as $s){
                        if( floatval($cz) >= $s['saving']){
                            $sum = $s['num'];
                        }else{
                            break;
                        }
                    }
                    $user_sum = Db::name('bonus_user')->where('username',$username)->whereTime('time', 'd')->field('id')->count();
                    $sum -= $user_sum;
                    if($sum <= 0){
                        $ret['ResultMsg'] = '您的抢红包次数不足!';
                    }else{
                        $lv = 0;
                        $new_money = false;
                        //判断是哪种红包类型
                        if($on_lay['flip'] == 1){
                            $bonus_lv = Db::name('bonus')->order('lv asc')->select();
                            foreach ($bonus_lv as $b){
                            	$cz = Db::name('chongzhi_list')->whereTime('cztime','today')->where(['username'=>$username,'zt'=>1])->value('SUM(je)');
                                if( floatval($cz) >= $b['min_saving']){
                                    if( floatval($cz) <= $b['max_saving']){
                                        $lv = $b['lv'];
                                    }else{
                                        continue;
                                    }
                                }else{
                                    break;
                                }
                            }
                            if($lv == 0){
                                $ret['ResultMsg'] = '您的充值金额不满足当前抢红包的条件!';
                            }else{
                                $bonus_chance = Db::name('bonus_chance')->where('lv',$lv)->column('chance,min_money,max_money');
                                $win = getWin($bonus_chance,'chance');
                                if(count($bonus_chance)<1){
                                    $ret['ResultMsg'] = '您的存款金额不满足抢红包条件!';
                                }else{
                                    $min_money = $bonus_chance[$win]['min_money'];
                                    $max_money = $bonus_chance[$win]['max_money'];
                                    $money= mt_rand($min_money*100,$max_money*100)/100;
                                    $new_money  = sprintf("%.2f",$money);
                                }
                            }
                        }else if($on_lay['flip'] == 2){
                            $bonus_chance = mt_rand(1, 100);
                            $win = Db::name('bonus_chance')->where(array('lv'=>$user['us_class'],'type'=>2))->field('chance,min_money,max_money,chance_money')->find();
                            if(empty($win)){
                                $ret['ResultMsg'] = '您所在的等级暂时无法抢红包!';
                            }else{
                                if($bonus_chance <= $win['chance']){
                                    $new_money = $win['chance_money'];
                                }else{
                                    $money= mt_rand($win['min_money']*100,$win['max_money']*100)/100;
                                    $new_money  = sprintf("%.2f",$money);
                                }
                            }
                        }
                        if( false !== $new_money ){
                            if( $new_money ){
                                Db::startTrans();
                                try{
                                    $data = array();
                                    $data['username'] = $username;
                                    $data['je'] = $new_money;
                                    $data['lv'] = $user['us_class'];
                                    $data['type'] = $on_lay['flip'];
                                    $data['time'] = time();
                                    if( !Db::name('bonus_user')->insert($data) ){
                                        throw new Exception('红包信息更新错误！');
                                    }
                                    if( !Db::name('username')->where('username', $username)->setInc('je', $new_money) ){
                                        throw new Exception('用户信息更新错误！');
                                    }
                                    $ret['result'] = 1;
                                    $ret['datas'] = array(
                                        'num' => $sum-1,
                                        'money' => $new_money
                                    );
                                    Db::commit();
                                }catch (\Exception $e) {
                                    $ret['ResultMsg'] = $e->getMessage();
                                    Db::rollback();
                                }
                            }
                        }
                    }
                }else{
                    $ret['ResultMsg'] = '未到开奖时间<br/>开奖时间为'.$on_lay['start_time'].'-'.$on_lay['end_time'];
                }
            }
        }
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function runLottery(){
        $czid = input("czid",0);
        $ret = array(
            'result' => 0,
            'ResultMsg' => ''
        );
        if( empty($czid) ){
            $ret['ResultMsg'] = '彩种信息错误！';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        $history = Db::name('kjjg_list')->field("qihao,jztime,kjjg")->where('czid',$czid)->where('kjjg','<>','0')->order('jztime DESC')->limit(20)->select();
        $history = array_map(function($v) use ($czid){
            $v['kjjg'] = kjjg_split($v['kjjg'],$czid);
            if( 9==$czid || 73==$czid ){
                $arr = $v['kjjg'];
                $tail = array_pop($arr);
                array_splice($v['kjjg'],-1,1,"+");
                array_push($v['kjjg'],$tail);
            }
            return $v;
        },$history);
        $ret['result'] = 1;
        $ret['datas'] = $history;
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function nowLottery(){
        $czid = input("czid",0);
        $ret = array(
            'result'=>0,
            'ResultMsg' => ''
        );
        if( empty($czid) ){
            $ret['ResultMsg'] = '请求参数错误';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        $redis = new Redis();
        $before_redis = $redis->get('secend_'.$czid);
        if($before_redis) {
            $detail = Db::name('kjjg_list')->where(['czid'=>$czid,'qihao'=>$before_redis])->field("qihao,kjjg,jztime")->find();
        }else{
            $detail = Db::name('kjjg_list')->where('czid',$czid)->where('jztime','<',time())->field("qihao,kjjg,jztime")->order('jztime','DESC')->find();
        }
        if( empty($detail) ){
            $ret['ResultMsg'] = '暂无开奖信息';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        if( empty($detail['kjjg']) ){
            $detail['kjjg'] = [];
        }else{
            $detail['kjjg'] = kjjg_split($detail['kjjg'],$czid);
            if( 9==$czid ){
                $arr = $detail['kjjg'];
                $tail = array_pop($arr);
                array_splice($detail['kjjg'],-1,1,"+");
                array_push($detail['kjjg'],$tail);
            }
        }
        $ret['result'] = 1;
        $ret['datas'] = $detail;
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function trend(){

        $czid = input('czid');
        $ret = array(
            'result'=>0,
            'type' => '',
            'ResultMsg' => ''
        );
        if( empty($czid) ){
            $ret['ResultMsg'] = '请求参数错误';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        $zoushi = Db::name('kjjg_list')->where('czid',$czid)->where("kjjg>'0'")->order('qihao','DESC')->limit(25)->select();

        $config = config("lotterys");
        foreach($config as $k=>$val){
            if( in_array($czid,$val) ){
                $ret['type'] = $k;
                break;
            }
        }
        $trend = new Trend();
        if($czid == 1 || $czid == 8 || $czid == 62 || $czid == 2 ){
            $zoushi = $trend->getSscTrend($zoushi,$czid);
        }else if($czid == 4 || $czid == 61 || $czid == 63){
            $zoushi = $trend->getPk10Trend($zoushi,$czid);
        }else if($czid == 36 || $czid == 44 || $czid == 72 || $czid == 39 || $czid == 40 || $czid == 41 || $czid == 43 || $czid == 46 || $czid == 47){
            $zoushi = $trend->getK3Trend($zoushi,$czid);
        }else if($czid == 16 || $czid == 25 || $czid == 28 || $czid==29){
            $zoushi = $trend->get11x5Trend($zoushi,$czid);
            if(isset($zoushi['type'])) $zoushi['type'] = array_values($zoushi['type']);
            $zoushi['data'] = array_map(function($v){
                $bottom = array_pop($v['dat_type']);
                $v['dat_type'] = [implode(",",$v['dat_type']),$bottom];
                return $v;
            },$zoushi['data']);
        }else if($czid == 5 || $czid == 7 || $czid == 48){
            $zoushi = $trend->getDpcTrend($zoushi,$czid);
        }else if($czid == 10){
            $zoushi = $trend->getPcddTrend($zoushi,$czid);
        }else if($czid == 9 || 73==$czid){
            $zoushi = $trend->getHk6Trend($zoushi,$czid);
        }else if($czid == 51){
            $zoushi = $trend->getQxcTrend($zoushi,$czid);
        }
        $ret['result'] = 1;
        $ret['datas'] = $zoushi;
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function orientation(){
        $czid = input('czid');
        $position = input('position',1);
        $ret = array(
            'result'=>0,
            'ResultMsg' => ''
        );
        if( empty($czid) ){
            $ret['ResultMsg'] = '请求参数错误';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        //生成走势图表
        $KjjgList = new \app\index\logic\KjjgList();
        $data = $KjjgList->getTrendJson($czid, $position);
        $data_attr = json_decode($data,true);
        if(empty($data_attr)){
            $data_attr = [];
        }else{
            if( isset($data_attr['RecordCount']) ) unset($data_attr['RecordCount']);
            if( isset($data_attr['Records']) ){
                $data_attr['Records'] = array_map(function($v) use($czid){
                    $count = count($v);
                    $v['list'] = [];
                    for($i=1; $i<=$count-3; $i++){
                        $position = $i;
                        if($czid == 1 || $czid == 8 || $czid == 62 || $czid == 5 || $czid == 7|| $czid == 10 || $czid==51 || $czid==2){
                            $position =$i-1;
                        }
                        if( 0==intval($v['iYL'.$position]) ){
                            $v['iYL'.$position] = $v['iOpenNum'];
                            $v['iOpenNum'] = $i;
                        }
                        if( 48==$czid && $v['iOpenNum']>6 ) $v['iOpenNum']=0;
                        $v['list'][] = $v['iYL'.$position];
                        unset($v['iYL'.$position]);
                    }
                    if( isset($v['sGamePeriods']) ) unset($v['sGamePeriods']);
                    return $v;
                },$data_attr['Records']);
            }

            if(isset($data_attr['Func']) ) unset($data_attr['Func']);
            if(isset($data_attr['Result']) ) unset($data_attr['Result']);
            if(isset($data_attr['Desc']) ) unset($data_attr['Desc']);
            $data_attr['avg'] = [];
            $data_attr['max'] = [];
            $data_attr['code'] = 0;
            $data_attr['range'] = 0;
            $data_attr['header'] = [];
            if($czid == 1 || $czid == 8 || $czid == 62 || $czid == 2){
                $data_attr['code'] = 5;
                $data_attr['range'] = 10;
                for($i=0; $i<10; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $p = $i;
                    62==$czid && $p+=1;
                    $data_attr['header'][] = strval($p);
                }
            }else if($czid == 4 || $czid == 61 || $czid == 63){
                $data_attr['code'] = 10;
                $data_attr['range'] = 10;
                for($i=1; $i<=10; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $p = $i;
                    63==$czid && $p-=1;
                    $data_attr['header'][] = strval($p);
                }
            }else if($czid == 36 || $czid == 44 || $czid == 72 || $czid == 39 || $czid == 40 || $czid == 41 || $czid == 43 || $czid == 46 || $czid == 47){
                $data_attr['code'] = 3;
                $data_attr['range'] = 6;
                for($i=1; $i<=6; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i);
                }
            }else if($czid == 16 || $czid == 25 || $czid == 28 || $czid == 29){
                $data_attr['code'] = 5;
                $data_attr['range'] = 11;
                for($i=1; $i<=11; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = str_pad(strval($i),2,"0",STR_PAD_LEFT);
                }
            }else if($czid == 5 || $czid == 7){
                $data_attr['code'] = 3;
                $data_attr['range'] = 10;
                for($i=0; $i<10; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i);
                }
            }else if($czid == 48){
                $data_attr['code'] = 3;
                $data_attr['range'] = 6;
                for($i=1; $i<=6; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i);
                }
            }else if($czid == 10){
                $data_attr['code'] = 3;
                $data_attr['range'] = 10;
                for($i=0; $i<10; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i);
                }
            }else if($czid == 9 || $czid == 73){
                $data_attr['code'] = 7;
                $data_attr['range'] = 50;
                $data_attr['max'] = [];
                $data_attr['avg'] = [];
                for($i=1; $i<=50; $i++){
//                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
//                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i-1);
                }
            }else if($czid == 51){
                $data_attr['code'] = 7;
                $data_attr['range'] = 10;
                for($i=0; $i<10; $i++){
                    $data_attr['max'][] = $data_attr['iYLMax'.$i];
                    unset($data_attr['iYLMax'.$i]);
                    $data_attr['avg'][] = $data_attr['iYLAvg'.$i];
                    unset($data_attr['iYLAvg'.$i]);
                    $data_attr['header'][] = strval($i);
                }
            }
        }
        //输出数据
        $ret['result'] = 1;
        $ret['datas'] = $data_attr;
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function introduce(){
        $czid = input('czid');
        $ret = array(
            'result'=>0,
            'ResultMsg' => ''
        );
        if( empty($czid) ){
            $ret['ResultMsg'] = '请求参数错误';
            return json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
        $czids = Db::name('lottery_classify')->where("czids REGEXP '(^|,){$czid}($|,)'")->value('czids');
        $list = Db::name("play_func")->where('czid','in',explode(',',$czids))->field('func_name,func_desc')->select();
        $ret['result'] = 1;
        $ret['datas'] = $list;
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function hb_detail(){

        $ret = array(
            'result'=>0,
            'ResultMsg'=>'无信息',
        	'datas'=>[]
        );
        $username = input('username','');
        $login_key = input('login_key','');
        $user = Db::name('username')->where(['username'=>$username,'login_key'=>$login_key])->where('open', '<', 1)->find();
        if( empty($user) ){
            $ret['ResultMsg'] = '请先登录!';
        }else{
            $on_lay = Db::name('bonus_lay')->find();
            if( 0!=intval($on_lay['flip']) && (strtotime($on_lay['start_time']) < time() && strtotime($on_lay['end_time']) > time()) ){
                $cz = Db::name('chongzhi_list')->whereTime('cztime','today')->where(['username'=>$username,'zt'=>1])->value('SUM(je)');
                $sum = 0;
                $lay_sum = Db::name('bonus_num')->order('saving asc')->select();
                foreach ($lay_sum as $s){
                    if( floatval($cz) >= $s['saving']){
                        $sum = $s['num'];
                    }else{
                        break;
                    }
                }
                $user_sum = Db::name('bonus_user')->where('username',$username)->whereTime('time', 'd')->field('id')->count();
                $sum -= $user_sum;
                $ret['result'] = 1;
                $ret['datas']['guize'] = $lay_sum;
                $ret['datas']['num']=$sum>0?$sum:0;
                $ret['ResultMsg']='';


            }else{
                $ret['ResultMsg'] = '暂未开启红包';
            }
        }
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function favourable(){
        $list = Db::name('xt_yhhd_list')->field('id,title,pic,begin_time,end_time')->where('xianshi',1)->order('paixu','DESC')->select();
        $list = array_map(function($v){
            if( !empty($v['pic']) ) $v['pic'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/static/attachment/'.$v['pic'];
            return $v;
        },$list);

        $ret = array(
            'result'=>1,
            'datas'=>$list
        );
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function favourable_detail(){
        $id = input('id',0);
        $detail = Db::name('xt_yhhd_list')->find($id);
        if( empty($detail) ){
            $ret = array(
                'result'=>0,
                'ResultMsg'=>'信息传入错误',
            );
        }else{
            if( !empty($detail['pic']) ) $detail['pic'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/static/attachment/'.$detail['pic'];
            $detail['content'] = preg_replace('/(<img.+src=\"?.+)(\/ueditor\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i',"\${1}".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST']."/ueditor/\${3}",$detail['content']);
            $detail['content'] = preg_replace('/\"/', "'", $detail['content']);
            $ret = array(
                'result'=>1,
                'datas'=>$detail
            );
        }
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function lottery_type(){
        $ret = array(
            'result'=>1,
            'datas'=> Db::name('lottery_classify')->where(['status'=>1])->field('id,czids,class_name_lottery')->select()
        );
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function lottery_intr(){
        $id = input('id',0);
        $type = input('type',0); //0：大彩种，1：彩种
        $ret = array(
            'result'=>1,
            'datas'=>[
                'time' =>[],
                'intro' => []
            ]
        );
        if( 0==intval($type) ){
            $lot_info = Db::name('lottery_classify')->where(['id'=>$id])->field('id,czids')->find();
        }else{
            $lot_info = Db::name('lottery_classify')->where("czids REGEXP '(^|,){$id}($|,)'")->find();

        }
        if( !empty($lot_info) ){
            $ret['datas']['time'] = Db::name('caipai_list')->where('id','in',$lot_info['czids'])->field('cp_name_old,desc')->select();
            $ret['datas']['intro'] = Db::name("lottery_classify_intr")->where(['lot_id'=>$lot_info['id']])->order("orders asc")->column('desc');
        }
        return json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
}


